import { defineNoteConfig, defineNotesConfig } from 'vuepress-theme-plume'
import fs from 'fs'
import path from 'path'

// 动态生成 sidebar
const generateSidebar = (dir: string) => {
  const files = fs.readdirSync(dir)
  const readmeIndex = files.findIndex(file => file.toLowerCase() === 'readme.md')
  const sidebarItems = files
    .filter(file => file.endsWith('.md') && file.toLowerCase() !== 'readme.md')
    .map(file => {
      const fileName = file.replace(/\.md$/, '') // 去除 .md 后缀
      return fileName// 去除文件名开头的序号
    })

  if (readmeIndex !== -1) {
    sidebarItems.unshift('') // 将 README.md 放在第一个位置
  }
  return sidebarItems
}

// 自动读取 notes 目录下的子目录并生成 NoteConfig
const notesDir = path.join(__dirname, '../notes')
const noteConfigs = fs.existsSync(notesDir)
  ? fs.readdirSync(notesDir, { withFileTypes: true })
    .filter(dirent => dirent.isDirectory())
    .map(dirent => defineNoteConfig({
      dir: dirent.name,
      link: `/${dirent.name}/`,
      sidebar: generateSidebar(path.join(notesDir, dirent.name)) // 动态生成 sidebar
    }))
  : []

console.log('noteConfigs', noteConfigs);

export const notes = defineNotesConfig({
  dir: 'notes',
  link: '/',
  notes: noteConfigs,
})
